
package com.tideit.husai.ui.attack

import android.os.Bundle
import android.os.CountDownTimer
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import androidx.fragment.app.Fragment
import com.tideit.husai.R
import com.tideit.husai.databinding.FragmentAttackSimulationBinding

class AttackSimulationFragment : Fragment() {
    private var _binding: FragmentAttackSimulationBinding? = null
    private val binding get() = _binding!!
    private var countdownTimer: CountDownTimer? = null

    private val targets = listOf(
        "美国航母-罗斯福号",
        "美国驱逐舰-马斯廷号",
        "美国巡洋舰-普林斯顿号",
        "美国补给舰-拉帕汉诺克号",
        "美国两栖攻击舰-马金岛号"
    )

    private data class Weapon(
        val name: String,
        val accuracy: Int, // 命中率(1-100)
        val damage: Int,   // 伤害值(1-100)
        val speed: Int     // 速度等级(1-5)
    )

    private val weapons = listOf(
        Weapon("反舰弹道导弹", 70, 90, 5),
        Weapon("巡航导弹", 85, 60, 3),
        Weapon("无人机群", 60, 40, 2),
        Weapon("自杀式快艇", 50, 70, 1),
        Weapon("水雷", 30, 80, 0)
    )

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        android.util.Log.d("AttackSimulation", "onCreateView")
        _binding = FragmentAttackSimulationBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        android.util.Log.d("AttackSimulation", "onViewCreated")
        super.onViewCreated(view, savedInstanceState)
        
        // 验证资源加载
        try {
            val testRes = requireContext().getDrawable(R.drawable.ic_attack_success)
            android.util.Log.d("AttackSimulation", "资源加载成功: ic_attack_success")
        } catch (e: Exception) {
            android.util.Log.e("AttackSimulation", "资源加载失败: ${e.message}")
        }

        // 初始化目标选择器
        binding.targetSpinner.adapter = ArrayAdapter(
            requireContext(),
            android.R.layout.simple_spinner_item,
            targets
        ).apply {
            setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        }

        // 初始化武器选择器
        binding.weaponSpinner.adapter = ArrayAdapter(
            requireContext(),
            android.R.layout.simple_spinner_item,
            weapons.map { it.name }
        ).apply {
            setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        }

        // 模拟打击按钮点击事件
        binding.btnSimulateAttack.setOnClickListener {
            startCountdown()
        }
    }

    private fun startCountdown() {
        // 隐藏准备状态，显示倒计时
        binding.layoutWeaponReady.visibility = View.GONE
        binding.layoutCountdown.visibility = View.VISIBLE
        binding.layoutLaunching.visibility = View.GONE

        countdownTimer?.cancel()
        countdownTimer = object : CountDownTimer(5000, 100) {
            override fun onTick(millisUntilFinished: Long) {
                val seconds = (millisUntilFinished / 1000) + 1
                binding.tvCountdown.text = "${seconds}秒"
                val progress = (millisUntilFinished.toFloat() / 5000 * 100).toInt()
                binding.countdownProgress.progress = progress
            }

            override fun onFinish() {
                startLaunching()
            }
        }.start()
    }

    private fun startLaunching() {
        // 隐藏倒计时，显示发射状态
        binding.layoutCountdown.visibility = View.GONE
        binding.layoutLaunching.visibility = View.VISIBLE

        // 模拟发射过程
        android.os.Handler().postDelayed({
            completeAttack()
        }, 3000)
    }

    private fun completeAttack() {
        // 隐藏发射状态，显示结果
        binding.layoutLaunching.visibility = View.GONE
        binding.layoutWeaponReady.visibility = View.VISIBLE

        val target = binding.targetSpinner.selectedItem.toString()
        val weapon = weapons[binding.weaponSpinner.selectedItemPosition]
        simulateAttack(target, weapon)
    }

    private fun simulateAttack(target: String, weapon: Weapon) {
        val results = listOf(
            "成功命中目标，造成严重损坏",
            "部分命中目标，造成中等损坏",
            "被敌方拦截，攻击失败",
            "完美命中目标关键部位，目标完全摧毁"
        ).random()

        val damageReport = when(weapon.name) {
            "反舰弹道导弹" -> "弹道导弹以超音速命中目标 (命中率:${weapon.accuracy}% 伤害:${weapon.damage})"
            "巡航导弹" -> "巡航导弹精确打击目标 (命中率:${weapon.accuracy}% 伤害:${weapon.damage})"
            "无人机群" -> "无人机群饱和攻击目标 (命中率:${weapon.accuracy}% 伤害:${weapon.damage})"
            "自杀式快艇" -> "自杀式快艇近距离爆炸 (命中率:${weapon.accuracy}% 伤害:${weapon.damage})"
            else -> "水雷隐蔽攻击目标 (命中率:${weapon.accuracy}% 伤害:${weapon.damage})"
        }

        binding.tvSimulationResult.text = """
            目标: $target
            武器: ${weapon.name}
            结果: $results
            详情: $damageReport
            时间: ${java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(java.util.Date())}
        """.trimIndent()

        // 根据结果设置不同图片
        val imageRes = when(results) {
            "成功命中目标，造成严重损坏" -> R.drawable.ic_attack_success
            "部分命中目标，造成中等损坏" -> R.drawable.ic_attack_partial
            "被敌方拦截，攻击失败" -> R.drawable.ic_attack_failed
            else -> R.drawable.ic_attack_perfect
        }
        binding.ivAttackEffect.setImageResource(imageRes)
    }

    override fun onDestroyView() {
        countdownTimer?.cancel()
        _binding = null
        super.onDestroyView()
    }
}
